import { Injectable, NestMiddleware } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { isStr, isEmpty } from "st-common-core";
import { decryptByRsaPriKey, DesTripleHeaderNameConst } from "st-common-encrypt";
import { rsaCommonKeyPair } from "../../../rsa";
import { EnvNameEnum } from "../../env";

/**
 * 对请求头中加密请求数据的密钥进行解密，并将解密前的密钥设置到响应头中以便客户端解密的全局中间件
 */
@Injectable()
export class DecryptKeyMiddleware implements NestMiddleware {

  constructor(private readonly configService: ConfigService) {
  }

  use(req: any, res: any, next: () => void) {
    // 如果在环境变量中配置关闭了请求数据的加密
    if (!this.configService.get<boolean>(EnvNameEnum.REQ_DATA_IS_ENCRYPT)) return next();
    // 获取请求头对象
    const reqHeaders = req.headers;
    // 获取请求头中加密的密钥
    const key = reqHeaders[DesTripleHeaderNameConst.KEY];
    // 如果加密的密钥存在且不为空，则对其解密
    if (isStr(key) && !isEmpty(key)) {
      // 在响应头中设置未解密的密钥，以便客户端解密
      res.setHeader(DesTripleHeaderNameConst.KEY, key);
      // 解密密钥
      reqHeaders[DesTripleHeaderNameConst.KEY] = decryptByRsaPriKey(key, rsaCommonKeyPair.privateKey);
    }
    next();
  }
}
